<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" size="mini">
        <el-form-item>
          <el-input
            v-model="listQuery.name"
            placeholder="编号/委托人/当事人"
            clearable
            @keyup.enter.native="handleFilter"
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            style="min-width: 360px"
            v-model="listQuery.search_date"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        :data="letters"
        border
        v-loading="listLoading"
        fit
        size="small"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column
          v-for="column in tableColumns"
          :key="column.key"
          :label="column.title"
          :prop="column.key"
          align="center"
          :width="column.width ? column.width : ''"
          :formatter="dataFormatter"
        ></el-table-column>
        <el-table-column align="center" label="操作" width="200px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              v-if="scope.row.stamp_confirm != true"
              @click="handleEdit(scope)"
              >确认</el-button
            >
            <el-button
              type="success"
              size="mini"
              icon="el-icon-search"
              v-else
              @click="handleEdit(scope)"
              >查看</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getStampLetterList"
      />
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog :visible.sync="dialogVisible" :title="getTitle" width="800px">
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
        label-position="right"
        style="width: 95%; padding: 0 30px"
        status-icon
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="案件编号" prop="case_name">
              <el-input
                v-model="form.case_name"
                placeholder="案件编号"
                readonly
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="律师函编号" prop="code">
              <el-input
                type="text"
                v-model="form.code"
                placeholder="律师函编号"
                readonly
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="委托人" prop="client">
              <el-input
                type="text"
                v-model="form.client"
                placeholder="委托人"
                readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当事人" prop="party">
              <el-input v-model="form.party" placeholder="当事人" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              v-if="form.case_type == 2 || form.case_type == 5"
              label="罪名"
              prop="reason"
            >
              <el-input v-model="form.reason" placeholder="罪名" readonly />
            </el-form-item>
            <el-form-item v-else label="案由" prop="reason">
              <el-input v-model="form.reason" placeholder="案由" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="法院" prop="court">
              <el-input v-model="form.court" placeholder="法院" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="律师" prop="lawyer">
              <el-input v-model="form.lawyer" placeholder="律师" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="审级" prop="level">
              <el-input v-model="form.level" placeholder="审级" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="律所名称" prop="office_name">
              <el-input
                v-model="form.office_name"
                placeholder="律所名称"
                readonly
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="申请人" prop="user_name">
              <el-input
                v-model="form.user_name"
                placeholder="申请人"
                readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请时间" prop="apply_time">
              <el-input
                v-model="form.apply_time"
                placeholder="申请时间"
                readonly
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="申请确认" prop="apply_confirm">
              <el-radio-group v-model="form.apply_confirm" disabled>
                <el-radio :label="true">确定</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="盖章确认" prop="stamp_confirm">
              <el-radio-group v-model="form.stamp_confirm">
                <el-radio :label="true">确定</el-radio>
                <el-radio :label="false">暂不</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          v-if="form.stamp_time == null"
          @click="handleSave()"
          >确认</el-button
        >
        <!-- <el-button
          type="primary"
          v-if="dialogType == 'new'"
          @click="handleSave(true)"
          >保存并新增</el-button
        > -->
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getStampLetters, updateStampLetter } from "@/api/case";
import { formatDateTime } from "@/utils/datetime";
import Pagination from "@/components/Pagination";

const defaultForm = {
  id: null,
  code: "",
  case: null,
  case_name: "",
  court: "",
  client: "",
  party: "",
  lawyer: null,
  reason: "",
  apply_confirm: null,
  user: null,
  stamp_user: null,
  stamp_confirm: null,
};

export default {
  name: "StampLetter",

  data() {
    return {
      form: Object.assign({}, defaultForm),
      formRules: {
        stamp_confirm: [
          {
            type: "boolean",
            required: true,
            message: "请选择申请确认",
            trigger: "blur",
          },
        ],
      },
      tableColumns: [
        {
          key: "code",
          title: "律师函编号",
        },
        {
          key: "case_name",
          title: "案件编号",
        },
        {
          key: "client",
          title: "委托人",
        },
        {
          key: "party",
          title: "当事人",
        },
        {
          key: "reason",
          title: "案由/罪名",
        },
        {
          key: "apply_time",
          title: "申请时间",
        },
        {
          key: "stamp_time",
          title: "盖章时间",
        },
      ],
      title: "律所函",
      dialogVisible: false,
      dialogType: "new",
      letters: [],
      cases: [],

      apply_time: null,

      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 15,
        name: null,
        search_date: "",
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["uid"]),
    getTitle() {
      return this.dialogType == "new"
        ? `新增${this.title}`
        : `${this.title}盖章确认`;
    },
  },
  components: {
    Pagination,
  },
  created() {
    this.getStampLetterList();
    // this.getCaseList();
  },
  methods: {
    getStampLetterList() {
      this.listLoading = true;
      getStampLetters(this.listQuery)
        .then((res) => {
          this.letters = res.results;
          this.listLoading = false;
          this.total = res.count;
        })
        .catch((error) => {
          console.log(error);
          this.$message.error("获取律师函信息失败!");
          this.listLoading = false;
        });
    },
    // getCaseList() {
    //   getAllCases().then((res) => {
    //     this.cases = res;
    //   });
    // },
    dataFormatter(row, column, cellValue, index) {
      if (column.property == "apply_time") {
        return formatDateTime(cellValue);
      } else if (column.property == "stamp_time") {
        return formatDateTime(cellValue);
      } else {
        return cellValue;
      }
    },
    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getStampLetterList();
    },
    // 增加
    handleAdd() {
      this.form = Object.assign({}, defaultForm);

      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 修改用户
    handleEdit(scope) {
      this.form = Object.assign({}, scope.row);
      this.form.apply_time = formatDateTime(scope.row.apply_time);
      this.dialogType = "edit";

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 删除用户
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该案件吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delLetter(row.id);
          this.letters.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 保存操作
    async handleSave() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        if (!this.form.stamp_user) {
          this.form.stamp_user = this.uid;
        }
        const res = await updateStampLetter(this.form);
        const index = this.letters.findIndex((v) => v.id === res.id);
        this.letters.splice(index, 1, res);

        const { code, client, party } = res;

        this.dialogVisible = false;

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>律师函: ${code}</div>
              <div>委托人: ${client}</div>
              <div>当事人: ${party}</div>
            `,
          type: "success",
        });
      });
    },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  // .el-table {
  //   margin-top: 10px;
  //   width: 100%;
  // }
}
</style>